var options, layer, table, form, upload, element, laytpl, uploads_url = $("#uploads_url").val(),
    admin_map = $("#admin_map").val();

layui.config({
    base: '/static/admin/js/' //静态资源所在路径
}).extend({
    index: 'lib/index',//主入口模块
}).use('index');

//layui初始化
layui.use(['form', 'upload', 'table', 'laypage', 'element', 'laytpl'], function () {
    var layer = layui.layer, form = layui.form, table = layui.table, upload = layui.upload, element = layui.element,
        laytpl = layui.laytpl, defaultColor, cs = $('.custom-style'), colorHtml = '';

    //设置默认主题色
    defaultColor = window.localStorage.getItem('defaultColor') ? window.localStorage.getItem('defaultColor') : '#16b777';
    colorHtml += '.layui-menu .layui-menu-item-checked .faster-title {color: ' + defaultColor + ' !important;}';
    colorHtml += '.layui-menu .layui-menu-item-checked:after {border-right: 3px solid ' + defaultColor + '  !important;}';
    colorHtml += '.layui-menu-item-checked2 .faster-title {background-color: ' + defaultColor + ' !important;}';
    colorHtml += '.layui-side-menu .child-menu .layui-menu .layui-menu-item-parent:hover > div {color: ' + defaultColor + ' !important;}';
    colorHtml += '.white-theme .layui-menu-item-checked2 .faster-title:hover {background-color: ' + defaultColor + ' !important;}';
    colorHtml += '.layui-laypage .layui-laypage-curr .layui-laypage-em { background-color: ' + defaultColor + ';}';
    colorHtml += '.layadmin-pagetabs .layui-tab-title li:after { background-color: ' + defaultColor + ';}';
    colorHtml += '.layadmin-pagetabs .layui-tab-title li .layui-tab-close:hover { background-color: ' + defaultColor + ';}';
    colorHtml += '.layui-btn { background-color: ' + defaultColor + ';}';
    cs.html(colorHtml);

    var t = window.localStorage.getItem('layuiAdmin'), rt = t ? JSON.parse(t) : '';
    rt && rt.theme ? $('.layui-side-menu').addClass(rt.theme.color.alias) : '';

    $(".nav_search input").keydown(function (e) {
        if (e.keyCode == 13) {
            table.reload('form_table', {
                where: form.val("search-form")
                , page: {
                    curr: 1
                }
            });
            $(".resetSearch").show();
            e.preventDefault();
            return false;
        }
    })

    // 监听全局builder - add,edit回车提交
    $(document).keydown(function (event) {
        var a = $, b = a('.builderSubmit');
        if (event.keyCode === 13) b.length > 0 ? b.click() : '';
    });


    form.on('submit(search)', function (data) {
        table.reload('form_table', {
            where: form.val("search-form")
            , page: {
                curr: 1
            }
        });
        $(".resetSearch").show();
        return false;
    });

    form.on('submit(resetSearch)', function (data) {
        $(".search-form")[0].reset();
        table.reload('form_table', {
            where: form.val("search-form")
            , page: {
                curr: 1
            }
        });
        $(".resetSearch").hide();
        return false;
    });


    table.on('tool(table)', function (obj) {
        try {
            tableTool(obj);
        } catch (e) {
            alert('发生错误了');
        }
    });

    //触发排序事件
    table.on('sort(table)', function (obj) {
        table.reload('form_table', {
            initSort: obj
            , where: {
                tableSortField: obj.field
                , tableSortOrder: obj.type
                , tableSearch: form.val("search-form")
            }
        });
    });
    //监听开关状态栏
    form.on('switch(status)', function (obj) {
        buttons.save(this.value, obj.elem.attributes[1].value, obj.elem.checked, $("#update_url").val());
    });
    form.on('switch(switch_old)', function (obj) {
        var val = $(this).prop('checked');
        var url = $(this).attr('url');
        $.get(url, {val: val})
    })
    form.on('switch(switch)', function (obj) {
        var val = $(this).prop('checked');
        var url = $(this).attr('url');
        $.get(url, {val: val})
    })
    //表单验证
    form.verify();

    form.on('select(tableInput)', function (obj) {
        tableInput($(obj.elem));
    });

    //添加配置页面，监听日期配置
    form.on('select(call_type)', function (obj) {
        if (obj.value == '7') {
            $("#time_format").css('display', 'block');
        } else {
            $("#time_format").css('display', 'none');
        }
    });

    //监听表单提交
    form.on('submit(save)', function (data) {
        layerLoad();
        var btn = $(this);
        btn.attr('disabled', true);
        formObj = $($(this).attr('formObj'));
        url = formObj.attr('action');
        var back_url = btn.attr('data-back-url');
        $.ajax({
            type: 'POST',
            url: url,
            data: formObj.serialize(),
            dataType: "json",
            success: function (data) {
                layer.closeAll();
                if (data.code == 1) {
                    notify.success(data.msg, 1000, function () {
                        if (back_url) {
                            parent.layui.index.refreshAndCloseTabs(back_url, true);
                        } else {
                            parent.layer.closeAll();
                            if (parent.$(".layui-table-page").length > 0) {
                                parent.layui.table.reload('form_table', {
                                    page: {
                                        curr: parent.$(".layui-laypage-em").next().text()  //主要代码行
                                    },
                                });
                            } else {
                                var w = window.frames.frameElement.id.includes('layui-layer-iframe');
                                w ? parent.location.reload() : location.reload();
                            }
                        }

                    });

                } else {
                    notify.error(data.msg);
                    btn.removeAttr('disabled');
                }
            },
            error(e) {
                layer.closeAll();
                btn.removeAttr('disabled');
            }
        });
        return false;
    })

    //单张图片上传
    upload.render({
        elem: '.uploadImage',
        url: uploads_url,
        before: function (obj) {
            layer.load();
            var showImage = this.item.find('.showImage');
            obj.preview(function (index, file, result) {
                showImage.attr('src', result)
            });
        },
        done: function (data) {
            layer.closeAll();
            if (data.code == 200) {
                this.item.find('.inpImage').val(data.data.url);
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        },
        error: function () {
            layer.closeAll('loading');
        }
    });

    $('.showImages').on('click', '.uploadDels', function () {
        $(this).parent('.w_imgCon').remove();
    }).on('click', '.uploadDels', function () {
        var i = $(this).index('.uploadDels');
        $('.uploadImageBoxes:eq(' + i + ')').remove();
    })


    $('.layui-card-body').on('click', '.openShowImg', function () {
        otherTool($(this), 'openShowImg');
    }).on('click', '.openEditor', function () {
        var value = $(this).attr("data-value");
        layer.open({
            type: 1,
            area: ['800px', '80%'],
            shade: 0.4,
            shadeClose: true,
            anim: 2,
            title: '预览',
            content: '<div style="padding: 10px">' + value + '</div>'
        });
    }).on('click', '.openVideo', function () {
        var value = $(this).attr("data-value");
        layer.open({
            type: 2,
            area: ['40%', '45%'],
            shade: 1,
            shadeClose: true,
            anim: 2,
            title: false,
            content: value
        });
    }).on('change', '.tableInput', function () {
        tableInput($(this));
    })


    /*列表页checkbox开始*/
    tableCheck = {
        init: function () {
            layui.use('form', function () {
                layui.form.on('checkbox(list_all)', function (obj) {
                    var checked = obj.elem.checked;
                    $("[lay-filter=list_checkbox]").prop("checked", checked);
                    layui.form.render('checkbox');
                })
            })
        },
        getData: function () {
            var arr = [];
            $("[lay-filter=list_checkbox]:checked").each(function (i, e) {
                arr.push($(this).val());
            });
            return arr;
        }
    }
    tableCheck.init();
    var cateIds = [];

    function getCateId(cateId) {
        $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
            id = $(el).attr('cate-id');
            cateIds.push(id);
            getCateId(id);
        });
    }

    $("tbody.x-cate tr[level!='0']").hide();

    //修改字段状态
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {

            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            cateIds = [];
            getCateId(cateId);

            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })


    /** 公共菜单树单个展开与合并 */
    $('.show_menu').click(function () {
        let state = $(this).attr('data-state');
        let id = $(this).attr('data-id');
        if (state === 'hide') {
            $(".pid_" + id).css('display', '');
            $(this).attr('data-state', 'show');
            $(this).html('&#xe625;');
        } else {
            $(".pp" + id).css('display', 'none').find('.show_menu').attr('data-state', 'hide').html('&#xe623;');
            $(this).attr('data-state', 'hide');
            $(this).html('&#xe623;');
        }
    });

});

let tableRender = function (id, cols, url, totalRow) {
    layui.table.render({
        elem: id
        , cols: [cols]
        , page: true
        , url: url
        , id: 'form_table'
        , totalRow: totalRow
        , cellMinWidth: 80
        , limit: 20
        , limits: [20, 40, 60, 80, 100]
        , size: 'sm'
        // , even: true
        // , skin: 'line'
        , done: function (res, curr, count) {
            if (res.census) {
                var html = '';
                for (var i = 0; i < res.census.length; i++) {
                    html += '<div>' + res.census[i].title + '：' + res.census[i].value + '</div>';
                }
                $(".statistics_list").html(html);
            }
            $(".layui-table-main tr").each(function (index, val) {
                $($(".layui-table-fixed-l .layui-table-body tbody tr")[index]).height($(val).height());
                $($(".layui-table-fixed-r .layui-table-body tbody tr")[index]).height($(val).height());
            });
        }
    });
}

let openDrawer = function (title, url, w, offset) {
    var anim = offset == 'r' ? 'slideLeft' : 'slideRight'
    layer.open({
        type: 2,
        offset: offset,
        anim: anim, // 从右往左
        area: [w, '100%'],
        shade: 0.3,
        shadeClose: true,
        id: 'ID-demo-layer-direction-r',
        title: [title, 'font-size:14px;color:#000;text-align: left;font-weight: bold'],
        content: url
    });
}

function layerLoad(text = '加载中....') {
    layer.msg('<div><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> ' + text + '', {
        shade: 0.8,
        time: 99999
    });
}


/** 菜单树全局展开与折叠 */
function openAllCate(that) {
    var text = $('.show_text').text();
    if (text == '展开') {
        $(".showAll").show();
        $('.show_text').text('折叠');
        $('.x-show').attr('status', 'false').html('&#xe625;');
    } else {
        $(".showAll").hide();
        $('.show_text').text('展开');
        $('.x-show').attr('status', 'true').html('&#xe623;');

    }

}

/** 公共获取表格内选中的数据 */
function getTable() {
    return layui.table.checkStatus('form_table');
}


/** 公共弹出层 */
function zhiju_show(title, url, w, h, full = 0) {
    if (title == null || title == '') title = false;
    if (url == null || url == '') url = "404.html";
    if (w == null || w == '' || $(window).width() < w) w = ($(window).width() * 0.9);
    if (h == null || h == '' || $(window).height() < h) h = ($(window).height() - 50);
    if (full == '1') {
        let index = layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url,

        });
        layui.layer.full(index);
    } else {
        layer.open({
            type: 2,
            area: [w + 'px', h + 'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade: 0.4,
            anim: 2,
            title: title,
            content: url
        });
    }
}


/** 公共删除 */
function destroys(obj, url, id, key, val) {
    layer.confirm('确认要删除吗？', function (index) {
        layer.load(2);
        $.post(url, {id: id, key: key, val: val}, function (data) {
            layer.closeAll();
            if (data.code == 1) {
                $(obj).parents("tr").remove();
                notify.success(data.msg);
            } else {
                notify.error(data.msg);
            }
        });
    });
}

$(".search_open").click(function () {
    var text = $(this).text();
    if (text == '展开') {
        $(".hidden").removeClass('layui-hide');
        $(this).text('收起').addClass('search_close').removeClass('search_open');
    } else {
        $(".hidden").addClass('layui-hide');
        $(this).text('展开').addClass('search_open').removeClass('search_close');
    }
});